package com.jzy.ssl.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.jzy.ssl.config.properties.WebsiteProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * SslCertificateExpireTask
 * Description：域名证书到期提醒定时任务
 *
 * @author JiangZhaoYong
 * @date 2024/12/5 16:21
 */
@Component
@Slf4j
public class SslCertificateExpireTask {

    @Resource
    private WebsiteProperties websiteProperties;

    @Scheduled(cron = "0 0 9 * * ?")
    public void task() {
        List<String> domainList = websiteProperties.getDomainList();
        domainList.forEach(domain -> {
            try {
                URL url = new URL("https://" + domain);
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.connect();
                X509Certificate certificate = (X509Certificate) connection.getServerCertificates()[0];
                Instant instant = certificate.getNotAfter().toInstant();
                LocalDateTime expiryDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                log.info(StrUtil.format("域名: {} SSL证书到期时间: {}", domain, LocalDateTimeUtil.format(expiryDate, "yyyy-MM-dd HH:mm:ss")));
                // 到达设置的预警时间 发送预警通知
                if (LocalDateTime.now().plusDays(websiteProperties.getWarnBeforeDay()).isAfter(expiryDate)) {
                    // 发送企业微信群通知预警
                    sendWeChatNotification(domain, expiryDate);
                }
            } catch (Exception e) {
                log.error("Error fetching SSL certificate for {}", domain);
                e.printStackTrace();
            }
        });
    }

    /**
     * 企业微信群通知
     *
     * @param domain     域名
     * @param expiryDate 到期时间
     * @author JiangZhaoYong
     * @date 2024/12/5 17:19
     */
    private void sendWeChatNotification(String domain, LocalDateTime expiryDate) {
        String message = "域名证书到期预警:域名【" + domain + "】的SSL证书将于【" + expiryDate.toLocalDate() + "】到期，请及时更新！";
        // 企业微信的通知请求体
        String payload = "{\n" + "  \"msgtype\": \"text\",\n" + "  \"text\": {\n" + "    \"content\": \"" + message + "\"\n" + "  }\n" + "}";
        // 使用 Hutool 发送 POST 请求
        if (CollectionUtil.isNotEmpty(websiteProperties.getWechatWebhookUrlList())) {
            websiteProperties.getWechatWebhookUrlList().forEach(webHookUrl -> {
                HttpRequest.post(webHookUrl).header("Content-Type", "application/json").body(payload).execute();
            });
        }
    }
}
